Page({
  data: {
    openid: ""
  },
  onLoad() {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.cloud.callFunction({
      name: "load"
    }).then(res => {
      // console.log(res.result.openid)
      var openid = res.result.openid
      wx.setStorageSync('openid', openid)
      console.log(openid)
      this.setData({
        openid
      })
      wx.cloud.callFunction({
        name: "getUser",
        data: {
          openid: this.data.openid
        }
      }).then(res => {
        //console.log(openid)
        console.log(res)
        var openid = this.data.openid
        console.log(openid)
        if (res.result.data.length == 0) {
          wx.showModal({
            content: "未注册",
            cancelColor: 'red'
          })
          //  this.loadByWechat()
          wx.cloud.callFunction({
            name: "addUser",
            data: {
              openid: openid
            }
          })
        } else {
          wx.switchTab({
            url: '../main/main',
          })
        }
      })

    })
    setTimeout(function () {
      wx.hideLoading()
    }, 1000)
  },

  loadByWechat() {
    wx.getUserProfile({
        desc: '用户完善会员资料',
      })
      .then(res => {
        console.log("用户允许了微信授权登录", res.userInfo);
      
        wx.switchTab({
          url: '../main/main',
        })
        //保存用户登录信息到缓存
        wx.setStorageSync('userInfo', res.userInfo)
        //初始化用户的收藏
        wx.cloud.callFunction({
          name:"initColl",
          data:{
            uid:this.data.openid
          }
        })
      })
      .catch(err => {
        console.log("用户拒绝了微信授权登录", err);
      })
  },
})